package com.suxii.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.suxii.netty_demo.R;
import com.suxii.netty_demo.activity.ChatActivity;
import com.suxii.pojo.MessageMsg;
import com.suxii.pojo.MyMsg;
import com.suxii.utils.Global;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder> {

    private List<MessageMsg> data;
    public Context context;

    //用联系人的uid，name；
    private Map<String, String> nameOfUid;

    private Map<Integer, MessageViewHolder> holderMap = new HashMap<>();
    private Map<Integer, Integer> mcout = new HashMap<>();

    public void reMoveCout(Integer uid, String con) {
        ((Activity) context).runOnUiThread(() -> {
            mcout.put(uid, 0);
            holderMap.get(uid).cout.setText(String.valueOf(mcout.get(uid)));
            holderMap.get(uid).text.setText(con);
        });

    }

    public void setMessageViewHolder(Integer uid, String con) {
        // 如果列表不存在就创建一个
        if (holderMap.get(uid) == null) {
            data.add(new MessageMsg(uid.toString(), con));
            ((Activity) context).runOnUiThread(() -> {
                notifyDataSetChanged();
            });
        } else {

            // 如果uid的key存在就+=1，否则就直接=1
            mcout.merge(uid, 1, Integer::sum);

            ((Activity) context).runOnUiThread(() -> {
                holderMap.get(uid).cout.setText(String.valueOf(mcout.get(uid)));
                holderMap.get(uid).text.setText(con);
                Log.e("aa", mcout.get(uid).toString());
            });
        }
        // 把发送人的uid作为文件名字，保存消息
        savaMessage(uid, con);
        //holderMap.get(uid).cout.setVisibility(View.VISIBLE);

    }

    public MessageAdapter() {
    }

    public MessageAdapter(List<MessageMsg> data, Context context) {
        this.data = data;
        this.context = context;

        findFriend();
        Log.e("aa", "构造");
    }

    private boolean isExist = false;

    private void findFriend() {
        File file = new File(context.getFilesDir(), "friend.sx");
        if (file.isFile()) {
            try (var fis = new FileInputStream(file);
                 var br = new BufferedReader(new InputStreamReader(fis))
            ) {
                String data;
                nameOfUid = new HashMap<>();

                while ((data = br.readLine()) != null) {
                    String[] s = data.split(" ");
                    nameOfUid.put(s[1], s[0]);
                }
                Global.nameOfUid = nameOfUid;

                isExist = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 删除消息 TODO 未完成待定
    public void removeMessage() {
        /*mcout.remove(uuid);
        holderMap.remove(uuid);
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getName().equals(String.valueOf(uuid))) {
                data.remove(i);
                return;
            }
        }
        notifyDataSetChanged();
        Log.e("aa",mcout.toString()+":"+holderMap.toString()+":"+data.toString());*/
        findMessage();
    }

    public void findMessage() {
        File file = new File(String.valueOf(context.getFilesDir()));
        List<MessageMsg> list = new ArrayList<>();
        File[] files = file.listFiles();
        Arrays.stream(files).filter(f -> f.getName().contains("message")).forEach(o -> {
            String name = o.getName().split("_")[0];
            try (
                    var bw = new BufferedReader(new FileReader(o))
            ) {
                String s;
                String s2 = "";
                while ((s = bw.readLine()) != null) {
                    s2 = s;
                }
                list.add(new MessageMsg(name, new Gson().fromJson(s2, MyMsg.class).getMessage()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        this.data = list;
        Global.messageMsgList = list;
        notifyDataSetChanged();
    }

    /*
  保存聊天信息到本地
   */
    public void savaMessage(Integer uuid, String ss) {
        String s = new Gson().toJson(new MyMsg(0, ss));
        Log.e("aa", s);
        File file = new File(context.getFilesDir(), uuid + "_message.sx");
        try (
                var bw = new BufferedWriter(new FileWriter(file, true))
        ) {
            bw.write(s);
            bw.newLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @NonNull
    @Override
    public MessageAdapter.MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_message, parent, false);
        return new MessageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MessageAdapter.MessageViewHolder holder, int position) {
        //holder.cout.setVisibility(holder.cout.getText().toString().equals("0")?View.GONE:View.VISIBLE);

        holderMap.put(Integer.parseInt(data.get(position).getName()), holder);

        //动态赋值
        if (!isExist) {
            findFriend();
        }
        String s = nameOfUid.get(data.get(position).getName());
        holder.name.setText(s != null ? s : data.get(position).getName());

        holder.text.setText(data.get(position).getCon());
        holder.itemView.setOnLongClickListener(view -> itemLongClickListener.onItemLongClick(view));
        holder.itemView.setOnClickListener(view -> {
            Global.uuid = Integer.valueOf(data.get(position).getName());
            //Global.name=s!=null?s:data.get(position).getName();
            Intent intent = new Intent(context, ChatActivity.class);
            context.startActivity(intent);

            holder.cout.setText("0");

            // holder.itemView.setScaleY((float) 1.1);
            // holder.itemView.setScaleX((float) 1.1);

            // 跳转动画
            /*ActivityOptionsCompat compat = ActivityOptionsCompat.makeCustomAnimation(context, R.anim.enter_up, R.anim.no_anim);
            ActivityCompat.startActivity(context,intent,compat.toBundle());*/

            // TODO 不应该移除，每次更新都会创建
            //mcout.remove(Integer.valueOf(data.get(position).getName()));

            //holder.cout.setVisibility(View.GONE);
        });
        //holder.cout.setVisibility(holder.cout.getText().equals("0")?View.GONE:View.VISIBLE);
    }

    //实现接口回调
    public interface ItemLongClickListener{
        boolean onItemLongClick(View view);
    }
    private ItemLongClickListener itemLongClickListener;
    public void setItemLongClickListener(ItemLongClickListener itemLongClickListener){
        this.itemLongClickListener=itemLongClickListener;
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class MessageViewHolder extends RecyclerView.ViewHolder {

        private TextView name;
        private TextView text;
        private TextView cout;

        public MessageViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.item_left_message_name);
            text = itemView.findViewById(R.id.item_message_text);
            cout = itemView.findViewById(R.id.item_message_cout);
        }
    }

}
